<template>
  <div>
    <button @click="sendMessage">发送消息</button>
    <div v-for="(msg, index) in messages" :key="index">{{ msg }}</div>
  </div>
</template>

<script>
import signalRService from '../services/signalrService'

export default {
  data() {
    return {
      messages: []
    }
  },
  async mounted() {
  try {
    await signalRService.startConnection()
    
    signalRService.addListener('ReceiveMessage', (message) => {
      this.messages.push(message)
    })
    
    // 添加连接状态监听
    signalRService.connection.onreconnecting(() => {
      this.$message.warning('连接断开，正在尝试重新连接...')
    })
    
    signalRService.connection.onreconnected(() => {
      this.$message.success('连接已恢复')
    })
    
  } catch (err) {
    this.$message.error('初始化连接失败: ' + err.message)
  }
},
  methods: {
    async sendMessage() {
      if (!signalRService.isConnected()) {
        this.$message.error('请等待连接建立后再发送消息')
        return
      }
      
      try {
        await signalRService.sendMessage('SendMessage', this.user, this.messageText)
        // ...其他处理
      } catch (err) {
        console.error('发送消息失败:', err)
      }
    }
  },
  beforeDestroy() {
    signalRService.stopConnection()
  }
}
</script>

<style>
</style>